import adminListV from "../view/adminList.ejs";
import adminTable from "../components/AdminTable.ejs"
import {getAdminList, postAdmin} from "../api/admin";
const addAdminBtnHandler = async function(){
	const adminName = document.adminForm.adminName.value;
	const password = document.adminForm.password.value;
	const rePassword = document.adminForm.rePassword.value;
	// 如果管理员账号不匹配正则
	if(!/^[a-z]+$/i.test(adminName)){
		toastr.error('管理员账号必须全部是英文！');
		return;
	}
	if(!/^\w+$/.test(password)){
		toastr.error('密码只支持英文，数字，下划线');
		return;
	}
	if(password !== rePassword){
		toastr.error('两次输入的密码必须一致！');
		return;
	}
	const data = await postAdmin({adminName,password});
	toastr.success(data.msg);
	// 1- 添加成功后需要更新管理员列表
	renderAdminList();
	// 2- 关闭弹出层，并清除表单内容
	document.adminForm.reset();// 清空表单
	document.querySelector("#adminCancelBtn").click()// 触发取消按钮的单击行为

}
const renderAdminList = async function(){
	const data = await getAdminList();
	document.querySelector("#adminTable").innerHTML = adminTable(data);
}
export default () => {
	return async (req, res) => {
		res.render(adminListV());
		document.querySelector("#addAdminBtn").onclick = addAdminBtnHandler;

		renderAdminList();
	}
}